package com.abaddon.controller;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeSupport;

import android.util.Log;
import android.view.MotionEvent;

import com.abaddon.view.Abaddon;
import com.abaddon.view.AbaddonMapView;
import com.google.android.maps.GeoPoint;

public class LongTouchController implements Runnable {

	private long startTime = 0;
	private long nowTime = System.currentTimeMillis();
	
	private int lastX = 0;
	private int lastY = 0;
	
	private boolean tagPlaced = false;
	private boolean hasMoved = false;
	
	private Abaddon abaddon = null;
	private AbaddonMapView abaddonMapView = null;
	
	public void setStartTime(long startTime) {
		this.startTime = startTime;
	}

	public void setNowTime(long nowTime) {
		this.nowTime = nowTime;
	}

	public void setLastX(int lastX) {
		this.lastX = lastX;
	}

	public void setLastY(int lastY) {
		this.lastY = lastY;
	}

	public void setTagPlaced(boolean tagPlaced) {
		this.tagPlaced = tagPlaced;
	}

	public void setHasMoved(boolean hasMoved) {
		this.hasMoved = hasMoved;
	}

	public LongTouchController(Abaddon abaddon, AbaddonMapView abaddonMapView){
		this.abaddon = abaddon;
		this.abaddonMapView = abaddonMapView;
	}
	
	public void onFingerDown(MotionEvent ev){
		startTime = System.currentTimeMillis();
		lastX = (int)ev.getX();
		lastY = (int)ev.getY();
		hasMoved = false;
	}
	
	public void onFingerMove(MotionEvent ev){
		if(lastX != (int)ev.getX() && lastY != (int)ev.getY()){	
			hasMoved = true;
		}
		lastX = (int)ev.getX();
		lastY = (int)ev.getY();
	}
	
	public void onFingerUp(MotionEvent ev){
		abaddonMapView.invalidate();
		tagPlaced = false;
		startTime = 0;
	}

	@Override
	public void run() {
		
		while(true){
			
			nowTime = System.currentTimeMillis();
			
			if(nowTime - startTime > 1000 && !hasMoved && !tagPlaced && startTime != 0){

				GeoPoint geoPoint = abaddonMapView.getProjection().fromPixels(lastX, lastY);
				
				Log.i("TESTING","firing event, geopoint = ");
				
				PropertyChangeEvent ae = new PropertyChangeEvent(this, AbaddonPropertyChangeValuesHolder.LONGPRESS, null, geoPoint);
				
				PropertyChangeSupport pcs = new PropertyChangeSupport(abaddon);
				
				pcs.addPropertyChangeListener(abaddon);
				pcs.firePropertyChange(ae);
				
				startTime = nowTime;
				tagPlaced = true;
				
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}